package com.tool;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author niuyicong
 * @date 2024/10/21  15:40:22
 * @description
 */

public class CyclicbarrierDemo {
    private static final Logger log = LoggerFactory.getLogger(CyclicbarrierDemo.class);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);

        CyclicBarrier barrier = new CyclicBarrier(2,()->{
            log.debug("task1,task2 finish......");
        });

        for (int i=0;i<3;i++){
            service.submit(() -> {
                log.debug("task1 begin...");
                try {
                    Thread.sleep(1000);
                    barrier.await();
                    //log.debug("task1 end...");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
            service.submit(() -> {
                log.debug("task2 begin...");
                try {
                    Thread.sleep(2000);
                    barrier.await();
                    //log.debug("task2 end...");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}
